package com.anysoft.base;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.anysoft.HostConstant;
import com.anysoft.MentorApplication;
import com.anysoft.MentorConst;
import com.anysoft.R;
import com.anysoft.StaticField;
import com.anysoft.bean.AccountLoginBean;
import com.anysoft.bean.BaseBean;
import com.anysoft.bean.OnlineCustomerBean;
import com.anysoft.bean.QueryFundInfoBean;
import com.anysoft.bean.ResultBean;
import com.anysoft.bean.SelectWarmPromptByTypeBean;
import com.anysoft.bean.UserBean;
import com.anysoft.linstener.OnNextLinstener;
import com.anysoft.other.SplashNewActivity;
import com.anysoft.utils.AnalyticsUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.PreferencesUtils;
import com.anysoft.utils.StatusBarUtils;
import com.anysoft.utils.StringUtils;
import com.anysoft.utils.login.PwdBeanUtil;
import com.anysoft.utils.user.UserBeanUtil;
import com.anysoft.view.dialog.IcbcDialog;
import com.anysoft.view.dialog.LoadingDialog;
import com.anysoft.web.OnlineCustomerActivity;
import com.anysoft.web.SelectWarmPromptByTypeActivity;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.zhy.autolayout.AutoLayoutActivity;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.anysoft.MentorConst.APP_CACAHE_DIRNAME;
import static com.anysoft.MentorConst.CUSTOMER_SERVICE_TELEPHONE_NUMBERS;
import static com.anysoft.utils.HttpUtils.getMD5;

/**
 * Created by wwq on 2016/11/16.
 */

public class BaseActivity extends AutoLayoutActivity {
    protected final String TAG = this.getClass().getSimpleName();
    protected int REQUEST_CODE_PERMISSION = 0x00099;
    public static final int MOD_USER_INFO = 1721;
    public static final int ADD_PLAN_BANK_CARD = 1722;
    public static final int MOD_USER_MOBILE = 1723;
    public BaseActivity mActivity = BaseActivity.this;

    public MentorApplication mentorApplication;
    public String minSdkVersion;
    private String periodYearOne;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mentorApplication = (MentorApplication) this.getApplication();
        minSdkVersion = Build.VERSION.SDK;

        try {
            EventBus.getDefault().register(this);
        } catch (Exception e) {
            MentorLogger.Log(TAG, "已订阅");
        }

        StatusBarUtils.setWindowStatusBarColor(mActivity, R.color.white);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    @Override
    protected void onResume() {
        super.onResume();
        AnalyticsUtils.onResumeToActivity(this);
        if (mentorApplication.needLogin()) {
            for (String className : MentorConst.listClassName) {
                if (className.equals(getClass().toString())) {
                    finish();
                    break;
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        AnalyticsUtils.onPauseToActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //取消注册事件
        EventBus.getDefault().unregister(this);
    }

    public void showToast(String msg) {
        if (StringUtils.isNullOrEmpty(msg) || msg.contains("网络加载失败，请稍后再试") || MentorConst.INTERNET_ERROR.equals(msg)) {
            return;
        }
        Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
    }

    public void signOut() {
        mentorApplication.signOut();
        clearSecretKey(mActivity);
    }

    /**
     * 获取uuid
     */
    public String getUUID() {
        final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

        final String tmDevice, tmSerial, androidId;
        tmDevice = "" + tm.getDeviceId();
//        tmSerial = "" + tm.getSimSerialNumber();//862258035659227
        androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(),
                android.provider.Settings.Secure.ANDROID_ID);

//        UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
        UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32));
        String uniqueId = deviceUuid.toString();
        uniqueId = TextUtils.isEmpty(uniqueId) ? "000000-000000-000000-uuid" : uniqueId;
        MentorLogger.Loge("UUID", uniqueId);
        return uniqueId;
    }

    public String getLoginUserId() {
        return mentorApplication.userBean == null ? "" : mentorApplication.userBean.getUserId();
    }

    public String getLoginUserIdByMD5() {
        return mentorApplication.userBean == null ? "" : getMD5(mentorApplication.userBean.getUserId());
    }

    public String getToken() {
        if (mentorApplication.userBean != null) {
            return mentorApplication.userBean.getToken();
        } else {
            return "";
        }
    }

    /**
     * 获取客户号
     *
     * @return
     */
    public String getFundCustomerNo() {
        if (mentorApplication.userBean != null) {
            return mentorApplication.userBean.getFundCustomerNo();
        } else {
            return "";
        }
    }

    /**
     * 保存密文
     *
     * @param pwd               手势密码或指纹密码
     * @param type              0--指纹密码，1--手势密码
     * @param context
     * @param internetSecretKey 网络密钥
     */
    public void saveSecretKey(String pwd, int type, Context context, String internetSecretKey, String password, String userId) {
        PwdBeanUtil.getInstance().savePwd(pwd, type, context, internetSecretKey, password, userId);
    }

    /**
     * 获取密码
     *
     * @param pwd               手势密码或指纹密码
     * @param type              0--指纹密码，1--手势密码
     * @param context
     * @param internetSecretKey 网络密钥
     */
    public String findPassword(String pwd, int type, Context context, String internetSecretKey, String userId) {
        return PwdBeanUtil.getInstance().findDate(userId, pwd, type, context, internetSecretKey);
    }

    /**
     * 返回密文用户id
     *
     * @return
     */
    public String findUserId() {
        return TextUtils.isEmpty(PreferencesUtils.getString(this, MentorConst.LAST_LOGIN_USER_ID, "")) ?
                UserBeanUtil.getInstance().findUserId() : PreferencesUtils.getString(this, MentorConst
                .LAST_LOGIN_USER_ID, "");
    }

    /**
     * 删除密文
     *
     * @param type 0--指纹密码，1--手势密码
     */
    public void deleteSecretKey(Context context, String userId, int type) {
        PwdBeanUtil.getInstance().deletePwd(context, userId, type);
    }

    /**
     * 清除密文
     */
    public void clearSecretKey(Context context) {
        PwdBeanUtil.getInstance().clearDate(context);
    }

    /**
     * 添加用户
     */
    public void saveUser(UserBean userInfo, AccountLoginBean accountLoginBean) {
        mentorApplication.setLoginInfoBean(userInfo, accountLoginBean);
        UserBeanUtil.getInstance().saveUser(userInfo);
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    public List<UserBean> findUserList() {
        return UserBeanUtil.getInstance().findUserList();
    }

    /**
     * 获取用户
     *
     * @return
     */
    public UserBean findUser(String userId) {
        return UserBeanUtil.getInstance().getUser(userId);
    }

    /**
     * 判断是否有登录过的用户
     *
     * @return true--有
     */
    public boolean hasUser() {
        return UserBeanUtil.getInstance().hasUser();
    }

    /**
     * 删除用户
     *
     * @param userId
     */
    public boolean deleteUser(String userId) {
        return UserBeanUtil.getInstance().deleteUser(userId);
    }

    public boolean isUserExist(String userId) {
        boolean isExit = UserBeanUtil.getInstance().isUserExist(userId);
        Logger.t(TAG).d("userId已存在-----" + isExit);
        return isExit;
    }

    public String getUserType(String userId) {
        return UserBeanUtil.getInstance().getUserType(userId);
    }

    public String getCustomerNo(String userId) {
        return UserBeanUtil.getInstance().getCustomerNo(userId);
    }

    public boolean getFingerPrintOpen(String userId) {
        return UserBeanUtil.getInstance().isFingerPrintOpen(userId);
    }

    public boolean getGestureOpen(String userId) {
        return UserBeanUtil.getInstance().isGestureOpen(userId);
    }

    public byte[] getGestureSalt(String userId) {
        return UserBeanUtil.getInstance().getSalt(userId);
    }

    public String getGestureRandomKey(String userId) {
        return UserBeanUtil.getInstance().getGestureRandomKey(userId);
    }

    public String getFingerPrintRandomKey(String userId) {
        return UserBeanUtil.getInstance().getFingerPrintRandomKey(userId);
    }

    public void clearFingerPrint(String userId) {
        UserBeanUtil.getInstance().clearFingerPrint(userId);
//        showToast("指纹关闭成功");
    }

    /**
     * 删除手势
     *
     * @param userId
     */
    public void clearGesture(String userId) {
        UserBeanUtil.getInstance().clearGesture(userId);
//        showToast("手势密码关闭成功");
    }

    public void clearUserPwd(String userId) {
        clearFingerPrint(userId);
        clearGesture(userId);
    }

    public void updateFingerPrint(UserBean userBean, String randomFKey) {
        UserBeanUtil.getInstance().updateFingerPrint(userBean, randomFKey);
        showToast("指纹设置成功");
    }

    /**
     * 设置和更新手势
     *
     * @param userBean
     * @param salt
     * @return
     */
    public void updateGesture(UserBean userBean, byte[] salt, String randomFKey) {
        UserBeanUtil.getInstance().updateGesture(userBean, salt, randomFKey);
        showToast("手势密码设置成功");
    }


    /**
     * 隐藏输入法
     *
     * @param windowToken
     */
    public void collapseSoftInputMethod(IBinder windowToken) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(windowToken, 0);
    }

    /**
     * 检查状态JavaBean，主要检查是否超时，超时了内部会做相应处理，即跳转到登录
     *
     * @param baseBean
     * @param result
     * @return 如果检查OK则返回true
     */
    public boolean checkState(BaseBean baseBean, String result) {
        return CommonUtil.checkState(this, baseBean, result);
    }

    /**
     * 检查状态JavaBean，主要检查是否超时，超时了内部会做相应处理，即跳转到登录
     *
     * @param baseBean
     * @param result
     * @return 如果检查OK则返回true
     */
    public ResultBean checkStateBean(BaseBean baseBean, String result) {
        return CommonUtil.checkStateBean(this, baseBean, result);
    }

    /**
     * 检查param是否为空
     *
     * @param params
     * @param param
     * @param paramDescribe
     * @return true--空
     */
    public boolean checkParam(Map<String, String> params, String paramTitle, String param, String paramDescribe) {
        boolean checkResult = TextUtils.isEmpty(param);
        if (checkResult) {
            showConfirmAlert(mActivity, "提示", paramDescribe);
        } else {
            params.put(paramTitle, param);
        }
        return checkResult;
    }

    public boolean checkParam(String param, String paramDescribe) {
        boolean checkResult = TextUtils.isEmpty(param);
        if (checkResult) {
            showConfirmAlert(mActivity, "提示", paramDescribe);
        }
        return checkResult;
    }

    public boolean checkParamLength(int sourceLength, int maxLength, String paramDescribe) {
        boolean checkResult = sourceLength > maxLength;
        if (checkResult) {
            showConfirmAlert(mActivity, "提示", paramDescribe);
        }
        return checkResult;
    }

    public long lastClickTime;

    /**
     * 防止暴力点击
     *
     * @return
     */
    public boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 1000) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public String getLocalSecretKey(Context context, String userId) {
        return getMD5(userId + SplashNewActivity.UUID + StaticField.getVersionName(context) + StaticField
                .getPackageName(context));
    }

    /**
     * 清除WebView缓存
     */
    public void clearWebViewCache() {

        //清理Webview缓存数据库
        try {
            deleteDatabase("webview.db");
            deleteDatabase("webviewCache.db");
        } catch (Exception e) {
//            e.printStackTrace();
            MentorLogger.Log(TAG, "清理Webview缓存数据库--失败");
            return;
        }

        //WebView 缓存文件
        File appCacheDir = new File(getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME);
        MentorLogger.Log(TAG, "appCacheDir path=" + appCacheDir.getAbsolutePath());

        File webviewCacheDir = new File(getCacheDir().getAbsolutePath() + "/webviewCache");
        MentorLogger.Log(TAG, "webviewCacheDir path=" + webviewCacheDir.getAbsolutePath());

        //删除webview 缓存目录
        if (webviewCacheDir.exists()) {
            deleteFile(webviewCacheDir);
        }
        //删除webview 缓存 缓存目录
        if (appCacheDir.exists()) {
            deleteFile(appCacheDir);
        }
    }

    /**
     * 递归删除 文件/文件夹
     *
     * @param file
     */
    public void deleteFile(File file) {

        MentorLogger.Log(TAG, "delete file path=" + file.getAbsolutePath());

        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            MentorLogger.Log(TAG, "delete file no exists " + file.getAbsolutePath());
        }
    }

    public void callCustomerServiceTelephoneNumbers() {
        IcbcDialog dialog = new IcbcDialog(this);
        dialog.setAnimationEnable(true);
        dialog.setCancelable(false);
        dialog.setTitle("提示");
        dialog.setContentText("您确定拨打该电话：400-811-9999");
        dialog.setEditTextType(false);
        dialog.setNegativeListener("取消", new IcbcDialog.OnNegativeListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
            }
        });
        dialog.setPositiveListener("拨打", new IcbcDialog.OnPositiveListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(CUSTOMER_SERVICE_TELEPHONE_NUMBERS));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);

                dialog.dismiss();
            }
        }).show();
    }

    /**
     * 获取在线客服URL
     */
    public void onlineCustomer() {
        Map<String, String> params = new HashMap<>();
        params.put("identityNo", mentorApplication.accountLoginBean == null ? "" : mentorApplication.accountLoginBean.getData().getIdentityNo());
        params.put("identityType", mentorApplication.accountLoginBean == null ? "" : mentorApplication.accountLoginBean.getData().getIdentityType());
        params.put("loginname", mentorApplication.accountLoginBean == null ? "" : mentorApplication.accountLoginBean.getData().getRealName());

        OkGo.<String>post(HostConstant.ONLINE_CUSTOMER)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new com.lzy.okgo.callback.StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateOnlineCustomer(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }


    public void UpdateOnlineCustomer(String json) {

        OnlineCustomerBean bean;
        try {
            bean = new Gson().fromJson(json, OnlineCustomerBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        if (bean == null || bean.getData() == null || TextUtils.isEmpty(bean.getData())) {
            showConfirmAlert(mActivity, "提示", getString(R.string.no_data));
            return;
        }

        Intent mIntent = new Intent();
        mIntent.putExtra("loadUrl", bean.getData());
        mIntent.putExtra("title", "在线客服");
        mIntent.setClass(mActivity, OnlineCustomerActivity.class);
        startActivity(mIntent);
    }


    /**
     * 用户风险等级
     */
    private String userLevel;

    /**
     * 设置用户风险等级
     */
    public void setUserLevel(String level) {
        this.userLevel = level;
    }

    /**
     * 获取用户风险等级
     *
     * @return
     */
    public String getUserLevel() {
        return this.userLevel;
    }

    /**
     * 启动风险评测界面 如评测过则启动 结果界面否则启动评测界面
     */
    public void startRiskActivity(String sLevel) {
        Intent intentRisk = null;
        if (StringUtils.isNullOrEmpty(sLevel)) {
//            intentRisk = new Intent(this, RiskEvaluationActivity.class);
        } else {
//            intentRisk = new Intent(this, RiskEvaluationResultActivity.class);
        }
        startActivity(intentRisk);
    }

    /**
     * <p>更新类型来获取温馨提示的数据
     * <p>
     * （必须）传 {'1': '登录页面',
     * '2': '开户页面',
     * '3': '绑卡页面',
     * '4': '更多-基金收益计算器页面',
     * '5': '货币-普通赎回页面',
     * '6': '短期理财-赎回页面',
     * '7': '基金产品-赎回页面',
     * '8': '货币-T+0赎回页面',
     * '9': '短期理财-预约赎回页面',
     * '10': '货币-申购页面',
     * '11': '非货币-申购页面',
     * '12': '转出页面',
     * '13': '转入页面',
     * '14': '认购页面',
     * '15': '超级现金快线-申购页面',
     * '16': '超级现金快线-赎回页面',
     * '17': '超级现金快线-T+0赎回页面',
     * '18': '设置分红方式页面',
     * '19': '撤单页面'
     * }
     */
    public void selectWarmPromptByType(String type) {
        Map<String, String> params = new HashMap<>();
        params.put("warmPromptType", type);
        OkGo.<String>post(HostConstant.SELECT_WARM_PROMPT_BY_TYPE)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new com.lzy.okgo.callback.StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateSelectWarmPromptByType(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }


    public void UpdateSelectWarmPromptByType(String json) {

        SelectWarmPromptByTypeBean bean;
        try {
            bean = new Gson().fromJson(json, SelectWarmPromptByTypeBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        if (bean == null || bean.getData() == null || bean.getData().getContent() == null) {
            showConfirmAlert(mActivity, "提示", getString(R.string.no_data));
            return;
        }

        Intent mIntent = new Intent();
        mIntent.putExtra("urlStr", bean.getData().getContent());
        mIntent.setClass(mActivity, SelectWarmPromptByTypeActivity.class);
        startActivity(mIntent);
    }

    private IcbcDialog showConfirmAlertDialog;

    public void showConfirmAlert(final Context context, String title,
                                 String content, String sbtn) {
        if (showConfirmAlertDialog == null && !((BaseActivity) context).isFinishing()) {
            showConfirmAlertDialog = new IcbcDialog(context);
            showConfirmAlertDialog.setColor("#FFFFFF");
            showConfirmAlertDialog.setCancelable(false);
            showConfirmAlertDialog.setAnimationEnable(true);
            showConfirmAlertDialog.setTitle(title);
            showConfirmAlertDialog.setContentText(content);
            showConfirmAlertDialog.setPositiveListener(sbtn, new IcbcDialog.OnPositiveListener() {
                @Override
                public void onClick(IcbcDialog dialog) {
                    showConfirmAlertDialog.dismiss();
                    showConfirmAlertDialog = null;
                }
            }).show();
        }
    }

    public void showConfirmAlertWithLinstener(final Context context, String title,
                                              String content, String sbtn) {
        if (showConfirmAlertDialog == null && !((BaseActivity) context).isFinishing()) {
            showConfirmAlertDialog = new IcbcDialog(context);
            showConfirmAlertDialog.setColor("#FFFFFF");
            showConfirmAlertDialog.setCancelable(false);
            showConfirmAlertDialog.setAnimationEnable(true);
            showConfirmAlertDialog.setTitle(title);
            showConfirmAlertDialog.setContentText(content);
            showConfirmAlertDialog.setPositiveListener(sbtn, new IcbcDialog.OnPositiveListener() {
                @Override
                public void onClick(IcbcDialog dialog) {
                    dialog.dismiss();
                    showConfirmAlertDialog = null;
                    if (mOnNextLinstener != null) {
                        mOnNextLinstener.OndoConfirm();
                    }
                }
            }).show();
        }
    }

    public void showConfirmAlert(final Context context, String title,
                                 String content, String sbtn1, String sbtn2) {
        if (showConfirmAlertDialog == null && !((BaseActivity) context).isFinishing()) {
            showConfirmAlertDialog = new IcbcDialog(context);
            showConfirmAlertDialog.setColor("#FFFFFF");
            showConfirmAlertDialog.setCancelable(false);
            showConfirmAlertDialog.setAnimationEnable(true);
            showConfirmAlertDialog.setContentTextGravity(Gravity.START);
            showConfirmAlertDialog.setTitle(title);
            showConfirmAlertDialog.setContentText(content);
            showConfirmAlertDialog.setEditTextType(false);
            showConfirmAlertDialog.setNegativeListener(sbtn1, new IcbcDialog.OnNegativeListener() {
                @Override
                public void onClick(IcbcDialog dialog) {
                    dialog.dismiss();
                    showConfirmAlertDialog = null;
                    if (mOnNextLinstener != null) {
                        mOnNextLinstener.OnConfirmNext(); //按钮1
                    }
                }
            });
            showConfirmAlertDialog.setPositiveListener(sbtn2, new IcbcDialog.OnPositiveListener() {
                @Override
                public void onClick(IcbcDialog dialog) {
                    dialog.dismiss();
                    showConfirmAlertDialog = null;
                    if (mOnNextLinstener != null) {
                        mOnNextLinstener.OnCancelNext(); //按钮2
                    }
                }
            });
            showConfirmAlertDialog.show();
        }
    }

    public void showConfirmAlert(final Context context, String title,
                                 String content) {
        showConfirmAlert(context, title, content, "确定");
    }

    public void showConfirmAlert(final Context context, String content) {
        showConfirmAlert(context, "提示", content, "确定");
    }

    private LoadingDialog loadingDialog;

    public void showLoading(Context context) {
        if (loadingDialog == null && !((BaseActivity) context).isFinishing()) {
            loadingDialog = new LoadingDialog(context);
            loadingDialog.setCancelable(false);
            loadingDialog.setAnimationEnable(true);
            loadingDialog.show();
        }
    }

    public void hideLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
    }

    /**
     * 当前用户输入是否完善   反洗钱
     *
     * @return
     */
    public boolean isUserDataPerfect() {
        if (mentorApplication == null || mentorApplication.accountLoginBean == null || mentorApplication.accountLoginBean.getData() == null) {
            return false;
        }
//        姓名、性别、证件类型、证件号码、证件有效期、省市、通讯地址、邮政编码、手机号、出生日期、职业（后期在法规销售适当性将增加字段）
        AccountLoginBean.DataBean accountLoginBean = mentorApplication.accountLoginBean.getData();
        String name = accountLoginBean.getRealName();
        String sex = accountLoginBean.getSex();
        String idType = accountLoginBean.getIdentityType();
        String idNo = accountLoginBean.getIdentityNo();
        String validEver = accountLoginBean.getCertificateValidEver();//是否长期有效 0否 1是
        String validTerm = accountLoginBean.getCertificateValidTerm();//有效期
//        String provinceCode  = accountLoginBean.getProvinceCode();//省
//        String cityCode  = accountLoginBean.getCityCode();//市
        String address = accountLoginBean.getContactAddress();//联系地址
        String postCode = accountLoginBean.getPostCode();//邮政编码
//        String mobileNo = accountLoginBean.getMobileNo();//手机号
//        String birthday = accountLoginBean.getBirthday();//出生日期
        String professionCode = accountLoginBean.getProfession();//职业
        if (StringUtils.isNullOrEmpty(name)
                || StringUtils.isNullOrEmpty(sex)
                || StringUtils.isNullOrEmpty(idType)
                || StringUtils.isNullOrEmpty(idNo)
//                ||StringUtils.isNullOrEmpty(provinceCode)
//                ||StringUtils.isNullOrEmpty(cityCode)
                || StringUtils.isNullOrEmpty(address)
                || StringUtils.isNullOrEmpty(postCode)
                || StringUtils.isNullOrEmpty(professionCode)) {
            return false;
        }
        if (StringUtils.isNullOrEmpty(validEver)) {
            return false;
        }
        if ("0".equals(validEver)) {
            if (StringUtils.isNullOrEmpty(validTerm)) {
                return false;
            }
        } else if ("1".equals(validEver)) {

        } else {//未知编码
            return false;
        }
        return true;
    }

    /**
     * 当前用户输入是否完善   反洗钱
     *
     * @return
     */
    public boolean isHavePhoneNumber() {
        if (mentorApplication == null || mentorApplication.accountLoginBean == null || mentorApplication.accountLoginBean.getData() == null) {
            return false;
        }
//        姓名、性别、证件类型、证件号码、证件有效期、省市、通讯地址、邮政编码、手机号、出生日期、职业（后期在法规销售适当性将增加字段）
        AccountLoginBean.DataBean accountLoginBean = mentorApplication.accountLoginBean.getData();
        String mobileNo = accountLoginBean.getMobileNo();//手机号
        if (StringUtils.isNullOrEmpty(mobileNo)) {
            return false;
        }
        return true;
    }

    /**
     * 查询基金详情
     */
    public void queryFundInfo(final String fundCode) {
//        Log.e("CallBack","获取基金详情"+fundCode);
        if (StringUtils.isNullOrEmpty(fundCode)) {
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("fundCode", fundCode);
        OkGo.<String>post(HostConstant.QUERY_FUND_INFO)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new com.lzy.okgo.callback.StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_fund(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void parseJson_fund(String json) {
        QueryFundInfoBean bean;
        try {
            bean = new Gson().fromJson(json, QueryFundInfoBean.class);
        } catch (Exception exception) {
            showConfirmAlert(this, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(this, bean, json)) {
            return;
        }

        if (bean == null || bean.getData() == null) {
            this.showConfirmAlert(this, "提示", getString(R.string.no_data));
            return;
        }
        QueryFundInfoBean.DataBean fundInfo = bean.getData();
        periodYearOne = fundInfo.getPeriodYearOne();
//        Log.e("lty", "getFundPeriodYearOne:=============近一年收益值============= " + periodYearOne);
    }

    public String getFundPeriodYearOne() {
        String fundYear;
        if (TextUtils.isEmpty(periodYearOne)) {
            fundYear = "";
        } else if (periodYearOne.contains("--")) {
            fundYear = "";
        } else {
            fundYear = periodYearOne;
        }
        return fundYear;
    }

    public String getRsaKey() {
        return getString(R.string.xjkx_public_key);
    }

    private OnNextLinstener mOnNextLinstener;

    public void setOnNextLinstener(OnNextLinstener onNextLinstener) {
        mOnNextLinstener = onNextLinstener;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    // 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    public HashMap<String, String> processParam(String param) {
        HashMap<String, String> urlParam = null;
        if (!TextUtils.isEmpty(param)) {
            urlParam = new HashMap<>();
            String[] strings = param.split("&");
            for (int i = 0; i < strings.length; i++) {
                String[] split = strings[i].split("=");
                for (int j = 0; j < split.length; j++) {
                    String key = split[0];
                    String value = "";
                    try {
                        value = split[1];
                    } catch (Exception exception) {
                        MentorLogger.Log(TAG, "value为null");
                    }
                    urlParam.put(key, value);
                }
            }
        }
        return urlParam;
    }
}
